﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Quartz;
using Quartz.Impl;
using System.Web;
using System.Configuration;
using System.Diagnostics;
using Dos.Common;
using Dos.ORM;
using Newtonsoft.Json;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
using Model;

namespace TimerTool
{
    public partial class FormMain : Form
    {
        //从工厂中获取一个调度器实例化
        IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
        //全家变量
        bool closeTag = true; 
          
        string jobName = "jobname";
        string tigerName = "tigername";
        string groupName = "groupname";

        public FormMain()
        {
            //限制一台电脑只能运行一个程序
            string proc = Process.GetCurrentProcess().ProcessName;
            Process[] processes = Process.GetProcessesByName(proc);
            if (processes.Length > 1)
            {
                MessageBox.Show("请不要运行多个定时系统！");
                Environment.Exit(0);
                return;
            }

            InitializeComponent();

            label2.Text = "未开始";
            string domain = System.Configuration.ConfigurationManager.AppSettings["domain"].ToString();
            string weid = System.Configuration.ConfigurationManager.AppSettings["weid"].ToString();
            string gl_openid = System.Configuration.ConfigurationManager.AppSettings["gl_openid"].ToString();


            //fsl f = new fsl();
            ////f.dts = DateTime.Now.Date.AddHours(20);
            //f.dojob();

            //return;

            string islocal = ConfigurationManager.AppSettings["islocal"].ToString();
            if (islocal == "1")
            {
                textBoxCron.Text = "0 0/5 * * * ?";
                label3.Text = textBoxCron.Text;
                label2.Text = "未开始";
            }
            else
            {
                textBoxCron.Text = "0 0/5 * * * ?";

                label3.Text = textBoxCron.Text;

                //开启调度器
                scheduler.Start();

                if (!scheduler.IsShutdown)
                {
                    label2.Text = "进程中";
                }
            }

        }

        private void buttonSure_Click(object sender, EventArgs e)
        {
           
            try
            {
                label3.Text = textBoxCron.Text;

                //先清除任务和触发器
                ClearJobTrigger();

                //触发器
                ITrigger trigger = TriggerBuilder.Create()
                                            .WithIdentity(tigerName, groupName)
                                            .StartNow()
                                            .WithCronSchedule(this.textBoxCron.Text.Trim())
                                            .Build();
                //任务
                IJobDetail job = JobBuilder.Create<MyJob>()
                                .WithIdentity(jobName, groupName)
                                //.UsingJobData("key", "value")
                                .Build();

                //启动
                scheduler.ScheduleJob(job, trigger);

                label2.Text = "进程中";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                label2.Text = "已停止";
            }

        }

        /// <summary>
        /// 清除任务和触发器
        /// </summary>
        private void ClearJobTrigger()
        {
            TriggerKey triggerKey = new TriggerKey(tigerName, groupName);
            JobKey jobKey = new JobKey(jobName, groupName);
            scheduler.PauseTrigger(triggerKey);// 停止触发器  
            scheduler.UnscheduleJob(triggerKey);// 移除触发器  
            scheduler.DeleteJob(jobKey);// 删除任务  
        }

        private void FormMain_Load(object sender, EventArgs e)
        {


            //string openid = "oM0rJ06gfBV3CoQDv4bO1viDSQAI";
            //string score = "21";

            //string key = "fl2008F@";
            //openid = Crypto3DES.Encrypt(openid, key);
            //openid = HttpUtility.UrlEncode(openid);
            //string score2 = HttpUtility.UrlEncode(Crypto3DES.Encrypt(score.ToString(), key));


            //string urlnew = "http://fl.0773-guilin.com/app/index.php?i=5&c=entry&do=sendTimer&m=aa_sr&openid=" + openid + "&score=" + score2;
            //string s = GetUrlData(urlnew);
            //MessageBox.Show(s);

        }

        public string GetUrlData(string Url)
        {

            System.Net.WebRequest hr = System.Net.HttpWebRequest.Create(Url);
            hr.Method = "GET";
            System.Net.WebResponse response = hr.GetResponse();
            System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
            string ReturnVal = reader.ReadToEnd();
            reader.Close();
            response.Close();
            return ReturnVal;
        }


        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            

            e.Cancel = true;
            NormalToMinimized();
        }

         

        //最小化    
        private void form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                NormalToMinimized();
            }
        }
         
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.MinimizedToNormal();
            }
        }

        private void MinimizedToNormal()
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            notifyIcon1.Visible = false;

        }
        private void NormalToMinimized()
        {
            this.WindowState = FormWindowState.Minimized;
            this.Visible = false;
            this.notifyIcon1.Visible = true;
        }


        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("是否退出？选否,最小化到托盘", "操作提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                if (!scheduler.IsShutdown)
                {
                    scheduler.Shutdown();
                }
                closeTag = false;
                //Application.Exit();
                Environment.Exit(0);
            }
        }
    }
}
